<?php

namespace Payment\Notify;

use Payment\Common\PayException;
use Payment\Common\FuConfig;
use Payment\Config;
use Payment\Utils\ArrayUtil;
use Payment\Utils\DataParser;

/**
 * Class FuNotify
 * @package Payment\Notify
 */
class FuNotify extends NotifyStrategy
{

    /**
     * SwNotify constructor.
     * @param array $config
     * @throws PayException
     */
    public function __construct(array $config)
    {
        parent::__construct($config);
        try {
            $this->config = new FuConfig($config);
        } catch (PayException $e) {
            throw $e;
        }
    }

    /**
     * 获取通知数据
     * @return array|bool
     */
    public function getNotifyData()
    {
        $params = [];
        $data = $_POST['req'] ?? file_get_contents('php://input');
        if (empty($data)) return false;
        $params = DataParser::toArray(urldecode($data));
        if (empty($params) || count($params) < 1) return false;
        foreach ($params as $key => &$value) $value = is_array($value) && empty($value) ? '' : $value;
        unset($value);
        return $params;
    }

    /**
     * 检查通知数据
     * @param array $data
     * @return bool
     * @throws \Exception
     */
    public function checkNotifyData(array $data)
    {
        if ($data['result_code'] != '000000') return false;
        return $this->verifySign($data);
    }

    /**
     * 检查数据是否被篡改过
     * @param array $retData
     * @return bool
     */
    protected function verifySign(array $retData)
    {
        $retSign = $retData['sign'] ?? '';
        return true;
    }

    /**
     * 封装回调函数需要的数据格式
     * @param array $data
     * @return array|false
     */
    protected function getRetData(array $data)
    {
        if ($this->config->returnRaw) return array_merge($data, ['channel' => Config::FU_CHARGE]);

        $retData = [
            'ins_cd' => $data['ins_cd'], //机构号
            'mchnt_cd' => $data['mchnt_cd'], //商户号
            'term_id' => $data['term_id'] ?? '', //终端号
            'user_id' => $data['user_id'] ?? '', //用户在商户的id
            'buyer_id' => $data['reserved_buyer_logon_id'] ?? '', //买家在渠道登录账号
            'pay_time' => date('Y-m-d H:i:s', strtotime($data['txn_fin_ts'])),//支付完成时间
            'amount' => $data['order_amt'], //订单金额
            'amount_settle' => $data['settle_order_amt'], //应结订单金额
            'transaction_id' => $data['transaction_id'] ?? '', //渠道交易流水号
            'order_no' => $data['mchnt_order_no'] ?? '', //商户订单号, 商户系统内部的订单号
            'return_param' => $data['reserved_addn_inf'] ?? '', //附加数据
            'channel' => Config::WX_CHARGE, //通道
        ];

        return $retData;
    }

    /**
     * replyNotify
     * @param bool $flag
     * @param string $msg
     * @return int
     */
    protected function replyNotify($flag, $msg = 'OK')
    {
        return ($flag ? 1 : 0);
    }
}
